﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Qreed.Windows.Forms;
using GotLyrics.Dialogs;
using System.Reflection;
using Qreed.Reflection;
using System.Diagnostics;
using Qreed.CodePlex;
using Qreed.Diagnostics;

namespace GotLyrics
{
    public partial class GotLyricsMainForm : Form
    {
        public GotLyricsMainForm()
        {
            InitializeComponent();

            Assembly asm = Assembly.GetExecutingAssembly();
            AssemblyFileVersionAttribute fileVersion = ReflectionHelper.GetAssemblyAttribute<AssemblyFileVersionAttribute>(asm);
            AssemblyTitleAttribute title = ReflectionHelper.GetAssemblyAttribute<AssemblyTitleAttribute>(asm);

            string details = string.Format("Fileversion: {0}{2}Path: {1}", fileVersion.Version.ToString(), asm.Location, Environment.NewLine);

            Log.Write("GotLyrics started.", details);

            CheckForNewVersion();

            Application.Idle += new EventHandler(ApplicationIdle);

            audioFileSelection.MainForm = this;
            audioFileSelection.SelectionChanged += new EventHandler<AudioFileSelectionChangeEventArgs>(audioFileList_SelectionChanged);
            
            // Create a context menu for the file list view that copies the edit menu on opening

            MenuToContextMenu contextMenu = new MenuToContextMenu(editToolStripMenuItem);
            audioFileSelection.ListView.ContextMenuStrip = contextMenu;

            generalPropertiesControl.MainForm = this;
            
            folderTreeView.PopulateTree();

            try
            {
                folderTreeView.SelectedPath = Settings.Default.LastFolder;
            }
            catch (Exception ex)
            {
                Log.Write("Failed to select last known folder.", ex.ToString(), LogLevel.Warning);
            }
        }

        private enum VersionCheckIntervalType
        {
            Never,
            Always,
            EachDay,
            EachWeek
        }

        private void CheckForNewVersion()
        {
            VersionCheckIntervalType interval = (VersionCheckIntervalType)Enum.Parse(typeof(VersionCheckIntervalType), Settings.Default.VersionCheckInterval);
            DateTime lastVersionCheck = Settings.Default.LastVersionCheck;
            TimeSpan ts = DateTime.Now.Subtract(lastVersionCheck);

            switch (interval)
            {
                case VersionCheckIntervalType.Never:
                    return;

                case VersionCheckIntervalType.Always:
                    break;

                case VersionCheckIntervalType.EachDay:
                    if (ts.Days < 1)
                        return;
                    break;

                case VersionCheckIntervalType.EachWeek:
                    if (ts.Days < 7)
                        return;
                    break;
            }

            versionChecker.CheckForNewVersionASync();
        }

        void CheckForNewVersionComplete(object sender, VersionCheckerEventArgs e)
        {
            if (e.Error != null)
            {
                // Log the message but die quietly
                Log.Write("Failed checking for a new version.", e.Error.ToString(), LogLevel.Warning);
                return;
            }

            Settings.Default.LastVersionCheck = DateTime.Now;

            Log.Write("Version check.",
                      "Local: " + versionChecker.LocalVersion.ToString() + Environment.NewLine +
                      "Online: " + versionChecker.OnlineVersion.ToString(),
                      LogLevel.Info);

            if (e.NewVersionAvailable)
            {
                string message = "A new version of GotLyrics has been found online.\r\nDo you wish to visit the homepage for more information?";

                if (DialogResult.Yes == MessageBox.Show(message, "New version available.", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    Process.Start(versionChecker.ProjectHomePage);
                }
            }
        }

        void ApplicationIdle(object sender, EventArgs e)
        {
            UpdateMenu();
        }

        private void UpdateMenu()
        {
            if (audioFileSelection.SelectedAudioFiles.Length > 0)
            {
                fromFilenamesToolStripMenuItem.Enabled = true;
                renameFilesToolStripMenuItem.Enabled = true;
            }
            else
            {
                renameFilesToolStripMenuItem.Enabled = false;
                fromFilenamesToolStripMenuItem.Enabled = false;
            }
        }

        void audioFileList_SelectionChanged(object sender, AudioFileSelectionChangeEventArgs e)
        {
            Log.DebugWrite("Selection changed.", e.Selection);
            generalPropertiesControl.SetSelection(e.Selection);
        }

        private void GotLyricsMainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Settings.Default.LastFolder = folderTreeView.SelectedPath;
            Settings.Default.Save();
        }

        private void folderTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            updateListViewTimer.Enabled = false;
            updateListViewTimer.Tag = folderTreeView.SelectedPath;
            updateListViewTimer.Start();
        }

        private void updateListViewTimer_Tick(object sender, EventArgs e)
        {
            Timer t = (Timer)sender;
            t.Enabled = false;

            // Hide the lower details pane 
            //splitContainerRight.Panel2Collapsed = true;

            audioFileSelection.SetCurrentFolder((string)t.Tag);
        }

        private void folderTreeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            e.Cancel = !audioFileSelection.CanChangeFolder();
        }
      
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (folderTreeView.Focused || audioFileSelection.ListView.Focused)
            {
                audioFileSelection.SelectAllItems();
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            audioFileSelection.SaveSelectedAudioFiles();
        }

        private void GotLyricsMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !audioFileSelection.CanChangeFolder();
        }

        private void saveAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            audioFileSelection.SaveAllModifiedAudioFiles();
        }

        private void fromFilenamesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GetTagsFromFilenamesDialog dlg = new GetTagsFromFilenamesDialog(audioFileSelection.SelectedAudioFiles, this);
            
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                
            }
        }

        private void renameFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (audioFileSelection.CanChangeFolder())
            {
                RenameFilesDialog dlg = new RenameFilesDialog(audioFileSelection.SelectedAudioFiles, this);

                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    if (!string.IsNullOrEmpty(dlg.CommonBaseFolder))
                    {
                        folderTreeView.SelectedPath = dlg.CommonBaseFolder;
                        audioFileSelection.SetCurrentFolder(folderTreeView.SelectedPath);
                        folderTreeView.RefreshSelectedNode();
                    }
                }
            }
        }

        private void Log_WriteMessage(object sender, Qreed.Diagnostics.LoggerEventArgs e)
        {
            Debug.WriteLine(e.ToLogString());

            if (e.Level == Qreed.Diagnostics.LogLevel.Error)
            {
                MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectTab(1);
            }
        }
    }

}